from django.contrib.auth.models import User
from django.contrib.postgres.fields import ArrayField
from django.db import models
from django.db.models.signals import post_save
from emotion import emotion
import logging

logger = logging.getLogger(__name__)


class GroupModel(models.Model):
    class Meta:
        db_table = "message_groups"
        verbose_name = "消息分组"
        verbose_name_plural = verbose_name

    name = models.CharField(max_length=100, verbose_name="组名")
    managers = models.ManyToManyField(to=User, verbose_name="管理", through='GroupMembersModel', related_name='Groups')

    def __str__(self):
        return str(self.name)


class MessageModel(models.Model):
    class Meta:
        db_table = "message"
        verbose_name = "信息"
        verbose_name_plural = verbose_name

    content = models.TextField(verbose_name="内容")
    words = models.TextField(verbose_name='分词',default='',blank=True)
    group = models.ForeignKey(GroupModel, on_delete=models.CASCADE, verbose_name='所属消息组', related_name="messages",
                              db_index=True)
    create_time = models.DateTimeField(verbose_name="上传时间", auto_now_add=True)

    label1 = models.CharField(max_length=20, verbose_name="一级情绪", default='', blank=True)
    prob1 = models.FloatField(verbose_name='一级情绪概率', default=0)
    label2 = models.CharField(max_length=20, verbose_name="二级情绪", default='', blank=True)
    prob2 = models.FloatField(verbose_name='二级情绪概率', default=0)
    remark = models.CharField(verbose_name='备注', default='', blank=True, max_length=100)
    uploader = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='上传用户', related_name="uploads",
                                 db_index=True)


class GroupMembersModel(models.Model):
    class Meta:
        db_table = "group_members"
        verbose_name = "小组成员"
        verbose_name_plural = verbose_name

    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="用户", related_name="joined_groups",
                             db_index=True)
    group = models.ForeignKey(GroupModel, on_delete=models.CASCADE, verbose_name="小组")
    upload = models.BooleanField(default=False, verbose_name="可上传")
    view = models.BooleanField(default=False, verbose_name="可查看")


from .dynamic import message_connections
from .serializers import MessageSerializer
import json
import jieba
import re
import os
stop_words = ''
def load_stopwords():
    global stop_words
    f_stop = open('stopwords.txt', encoding='utf-8')  # 中文停用词表
    stop_words = [line.strip() for line in f_stop]
    f_stop.close()

def get_words(text):
    remove_chars = '[·’!"\#$%&\'()＃！（）*+,-./:;<=>?\@，：?￥★、…．＞【】［］。《》？“”‘’\[\\]^_`{|}~]+'
    text = re.sub(remove_chars, "", text)  # 去标点
    text = jieba.cut(text)  # 分词
    if stop_words == '':
        load_stopwords()
    words = ''
    for word in text:
        if word not in stop_words and len(word) >1 :
            words = words + word + ' '
    return words
def analyse_emotion(sender, instance, created,**kwargs):
    if created:
        try:
            l1, p1, l2, p2 = emotion(instance.content)
            instance.label1 = l1
            instance.prob1 = p1
            instance.label2 = l2
            instance.prob2 = p2
            instance.save()
        except Exception as err:
            logger.critical("无法获取情绪{}".format(err))
        words = get_words(instance.content)
        if len(words)>=2:
            words=words[0:len(words)-1]
        instance.words=words#除去最后空格
        instance.save()
        if instance.group.name in message_connections:
            for con in message_connections[instance.group.name]:
                try:
                    con.send(json.dumps(MessageSerializer(instance).data))
                except Exception as err:
                    logger.critical("发送失败"+repr(err))


post_save.connect(analyse_emotion, MessageModel, weak=False)
